﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace STT.Admin
{
    /// <summary>
    /// Summary description for Upload
    /// </summary>
    public class Upload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            context.Response.Expires = -1;
            try
            {
                if (context.Request.Files.Count > 0)
                {
                    HttpFileCollection SelectedFiles = context.Request.Files;
                    string[] ids = new string[context.Request.Files.Count];

                    for (int i = 0; i < SelectedFiles.Count; i++)
                    {
                        HttpPostedFile postedFile = SelectedFiles[i];

                        string savepath = context.Server.MapPath(@"~\Uploads\Files\");
                        string filename = postedFile.FileName.Trim();

                        #region
                        //string savepath = "";
                        //string tempPath = "";
                        //tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
                        //savepath = context.Server.MapPath(tempPath);
                        //string filename = postedFile.FileName;
                        //if (!Directory.Exists(savepath))
                        //    Directory.CreateDirectory(savepath);
                        #endregion

                        string id = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString() + "¿" + filename;

                        ids[i] = id;

                        // luu file
                        postedFile.SaveAs(Path.Combine(savepath , id));
                    }

                    var serializer = new JavaScriptSerializer();
                    var json = serializer.Serialize(ids);
                    // Gui tra ket qua ten file ve
                    context.Response.Write(json);
                }
            }

            catch (Exception ex)
            {
                context.Response.Write("Error: " + ex.Message);
            }           
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}